package v1;

import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.types.Variant;
import java.util.HashMap;

class BluetoothSender {

    public void sendWifiStatus(String devicePath, String status, String message) {
        if (devicePath == null) {
            System.err.println("设备路径为空，无法发送蓝牙消息");
            return;
        }

        try {
            DBusConnection conn = DBusConnection.getConnection(DBusConnection.DEFAULT_SYSTEM_BUS_ADDRESS);

            sendViaMethodCall(conn, devicePath, status, message);

//            sendViaCommandLine(devicePath, status, message);

            conn.disconnect();

            System.out.println("蓝牙消息发送完成: " + status + " - " + message);

        } catch (Exception e) {
            System.err.println("通过蓝牙发送消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void sendViaMethodCall(DBusConnection conn, String devicePath, String status, String message) {
        try {
            // 调用设备的自定义方法（如果设备支持）
            String responseData = String.format("WIFI_RESULT|%s|%s|%d",
                    status, message, System.currentTimeMillis());
            byte[] data = responseData.getBytes();

            conn.sendMessage(new org.freedesktop.dbus.messages.MethodCall(
                    "org.bluez",
                    devicePath,
                    "org.bluez.Device1",
                    "SendMessage",
                    (byte) 1,
                    "aya{sv}",
                    new Object[]{data, new HashMap<String, Variant<?>>()}
            ));

            System.out.println("通过方法调用发送数据: " + responseData);

        } catch (Exception e) {
            System.err.println("通过方法调用发送失败: " + e.getMessage());
            // 这个方法可能不存在，是正常的
        }
    }

    private void sendViaCommandLine(String devicePath, String status, String message) {
        try {
            // 使用dbus-send命令行工具发送信号
            String signalData = String.format("STATUS:%s,MESSAGE:%s,TIME:%d",
                    status, message.replace(" ", "_"), System.currentTimeMillis());

            // 发送PropertiesChanged信号
            ProcessBuilder pb = new ProcessBuilder(
                    "dbus-send", "--system", "--type=signal", devicePath,
                    "org.freedesktop.DBus.Properties.PropertiesChanged",
                    "string:com.example.WiFiService",
                    "array:string:Status,Message",
                    "array:variant:string:" + status + ",string:" + message
            );

            Process process = pb.start();
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                System.out.println("通过命令行发送信号成功");
            } else {
                System.err.println("通过命令行发送信号失败，退出码: " + exitCode);
            }

        } catch (Exception e) {
            System.err.println("通过命令行发送失败: " + e.getMessage());
        }
    }

    private byte[] createManufacturerData(String status, String message) {
        try {
            // 创建制造商特定数据
            // 使用特定的制造商ID (0xFFFF 用于测试)
            String dataStr = "WIFI:" + status + ":" + message;
            byte[] dataBytes = dataStr.getBytes("UTF-8");

            // 制造商数据格式: [制造商ID低字节, 制造商ID高字节, 数据...]
            byte[] manufacturerData = new byte[dataBytes.length + 2];
            manufacturerData[0] = (byte) 0xFF; // 制造商ID低字节
            manufacturerData[1] = (byte) 0xFF; // 制造商ID高字节 (0xFFFF)
            System.arraycopy(dataBytes, 0, manufacturerData, 2, dataBytes.length);

            return manufacturerData;

        } catch (Exception e) {
            System.err.println("创建制造商数据失败: " + e.getMessage());
            return new byte[]{0x57, 0x49, 0x46, 0x49}; // "WIFI"
        }
    }
}